package com.cuit.xsc.weishare.logic;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;

import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.cuit.xsc.weishare.activity.BaseActivity;
import com.cuit.xsc.weishare.model.UserInfo;
import com.cuit.xsc.weishare.model.WeiboBean;
import com.cuit.xsc.weishare.services.StatusesService;
import com.cuit.xsc.weishare.util.BitmapGet;
import com.cuit.xsc.weishare.util.ConfigUtil;
import com.cuit.xsc.weishare.util.JsonHelper;
import com.cuit.xsc.weishare.util.LogUtil;
import com.cuit.xsc.weishare.util.MessageDialog;
import com.cuit.xsc.weishare.util.NetUtil;
import com.cuit.xsc.weishare.util.OAuth;
import com.cuit.xsc.weishare.util.OAuthConfigUtil;
import com.tencent.weibo.api.User_API;




public class MainService extends Service implements Runnable
{
	private static LinkedList<Task> tasks = new LinkedList<Task>();
	public static ArrayList<BaseActivity> allActivity = new ArrayList<BaseActivity>();
	private boolean isRun;
	OAuthConfigUtil oAuthConfigUtil = OAuthConfigUtil.getInstance();
	
	public static UserInfo currentUser;

	Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			BaseActivity baseActivity = null;
			String activityName = "";
			switch (msg.what)
			{
			case Task.GET_QQ_REQUEST_TOKEN:			
			case Task.GET_SINA_REQUEST_TOKEN:
				activityName = "AuthAct";
				break;
			case Task.GET_USER_HEAD:
				activityName = "SuccessAct";
				break;
			case Task.GET_NEW_HOME_TIMELINE:
			case Task.GET_OLD_HOME_TIMELINE:
			case Task.WEIBO_FRIEDNS_TIMELINE:
				activityName = "HomeAct";
				break;
			case Task.PUBLISH_WEIBO:
				activityName = "CreativeDesignAct";
				break;
			case Task.GET_PRIVATE_MESSAGE:
				activityName = "MsgAct";
				break;
			case Task.GET_USER:
			case Task.GET_SELFINFO_HEAD:
				activityName = "SelfInfoAct";
				break;
			case Task.ADD_PRIVATE_MSG:
				activityName = "PrivateMsgConversationAct";
				break;

			default:
				break;
			}
			baseActivity = getActivityByName(activityName);
			
			if (msg.arg1 == -1 && baseActivity != null)
			{
				Toast.makeText(baseActivity, "网络异常，请稍后再试！", Toast.LENGTH_SHORT).show();
			}
		
			if (baseActivity != null)
			{
				baseActivity.refresh(msg.what, msg.obj);		
			}
			else
			{
				System.out.println(activityName+" is null.");
			}
			
			
		};
	};

	@Override
	public void onCreate()
	{
		LogUtil.d(this, "onCreate");
		isRun = true;
		Thread thread = new Thread(this);
		thread.start();
	}
	
	@Override
	public void onDestroy()
	{
		isRun = false;
		super.onDestroy();
	}

	@Override
	public void run()
	{
		while (isRun)
		{
			//LogUtil.d(this, "running");
			
			Task task = null;
			if (!tasks.isEmpty())
			{
				LogUtil.d(this, "running task");
				task = tasks.poll();
				if (null != task)
				{
					doTask(task);
				}
			}
			try
			{
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}

	}

	private void doTask(Task task)
	{
//		Toast toast = new Toast(this);
//		Toast.makeText(this, "请求网络", Toast.LENGTH_SHORT).show();
		LogUtil.d(this, "doTask");
		Message msg = handler.obtainMessage();
		msg.what = task.getTaskID();
		boolean connect = isConnect(this);
		if (!connect)
		{
			msg.arg1 = -1;
			handler.sendMessage(msg);
			return;
		}
		
		
		switch (task.getTaskID())
		{
		case Task.GET_QQ_REQUEST_TOKEN:
			oAuthConfigUtil.initQqData();
			oAuthConfigUtil.setCurWeibo(OAuthConfigUtil.QQW);
			//init
		    OAuth  qqOAuth = OAuth.getInstance();
		    qqOAuth.clear();
		    
		    //获取被操作app的key、secret
	
		    qqOAuth.setKeyAndSecret(ConfigUtil.qq_AppKey, ConfigUtil.qq_AppSecret);
		    
		    String qqUrl = qqOAuth.getAuthorizUrl();
		    if (qqUrl.contains("oauth_token=null"))
			{
				qqUrl = null;
			}
			msg.obj = qqUrl;

			break;
		case Task.GET_SINA_REQUEST_TOKEN:
			oAuthConfigUtil.initSinaData();
			oAuthConfigUtil.setCurWeibo(OAuthConfigUtil.SINAW);
			OAuth  sinaOAuth = OAuth.getInstance();
		    sinaOAuth.clear();
		    
		    //获取被操作app的key、secret
	
		    sinaOAuth.setKeyAndSecret(ConfigUtil.sina_AppKey, ConfigUtil.sina_AppSecret);
		    
		    String sinaUrl = sinaOAuth.getAuthorizUrl();
			msg.obj = sinaUrl;
			break;
		case Task.GET_USER_HEAD:
			
			
			UserInfo userInfo = (UserInfo) task.getTaskParam().get("user");
			
			String headUrl = null;
			String type = userInfo.getUserType();
			LogUtil.i(this, "type="+type+"_"+type.equals(ConfigUtil.QQW));
			if (type.equals(ConfigUtil.QQW));
			{
				com.tencent.weibo.beans.OAuth qqOaAuth = new com.tencent.weibo.beans.OAuth();
				qqOaAuth.setOauth_token(userInfo.getToken());
				qqOaAuth.setOauth_token_secret(userInfo.getTokenSecret());
				User_API uApi = new User_API();
				String result = null;
				try
				{
					result = uApi.info(qqOaAuth, "json");
				}
				catch (Exception e)
				{
					LogUtil.e(this, "QQ get user head error.");
					e.printStackTrace();
				}
				
				headUrl = JsonHelper.getQQheadUrl(result);
				if (headUrl != null)
				{
					headUrl+="/"+ConfigUtil.QQ_HEAD_IMAGE_SIZE;
					userInfo.setUserId(JsonHelper.getQQopenId(result));
				}
			}
		    if (type.equals(ConfigUtil.SINAW)) 
			{
				System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
				Weibo sinaWeibo = new Weibo();
				sinaWeibo.setOAuthAccessToken(userInfo.getToken(), userInfo.getTokenSecret());
				sinaWeibo.setOAuthConsumer(ConfigUtil.sina_AppKey, ConfigUtil.sina_AppSecret);
				try
				{
					User sinaUser = sinaWeibo.showUser(userInfo.getUserId());
					if (sinaUser != null)
					{
						headUrl = sinaUser.getProfileImageURL().toString();
						userInfo.setUserName(sinaUser.getName());
					}
					
				}
				catch (WeiboException e)
				{
					LogUtil.e(this, "Sina get user head error.");
					e.printStackTrace();
				}
			}
		    
		   LogUtil.i(this, "headUrl="+headUrl);
		
			Drawable userIcon = NetUtil.getNetImage(headUrl);
			//userInfo.setUserName(user.getName());
			userInfo.setUserIcon(userIcon);
			
			msg.obj = userInfo;
			userInfo = null;
			
			
			
			break;
		case Task.WEIBO_FRIEDNS_TIMELINE:
			StatusesService service = new StatusesService(currentUser);
			msg.obj = service.getFriendsTimeline();
			break;
		case Task.PUBLISH_WEIBO:
			WeiboBean weiboBean = (WeiboBean)task.getTaskParam().get("weiboBean");
			StatusesService cservice = new StatusesService(currentUser);
			int res = cservice.publishWeibo(weiboBean);
			if (res == -1)
			{
				msg.obj = "failed";
			}
			else
			{
				msg.obj = "success";
			}
			break;
		case Task.GET_NEW_HOME_TIMELINE:
			long p = (Long) task.getTaskParam().get("p");
			StatusesService nservice = new StatusesService(currentUser);
			msg.obj = nservice.getNewTimeLine(p);
			/*try
			{
				Thread.sleep(3000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}*/
			break;
		case Task.GET_OLD_HOME_TIMELINE:
			long op = (Long) task.getTaskParam().get("p");
			StatusesService oservice = new StatusesService(currentUser);
			msg.obj = oservice.getOldTimeLine(op);
			break;
		case Task.GET_PRIVATE_MESSAGE:
			
			StatusesService privateMsgService = new StatusesService(currentUser);
			msg.obj = privateMsgService.recvPivateMessage();
			break;
		case Task.GET_USER:
			
			StatusesService selfInfoService = new StatusesService(currentUser);
			msg.obj = selfInfoService.getUser();
			break;
		case Task.GET_SELFINFO_HEAD:
			String url = (String) task.getTaskParam().get("url");
			Bitmap bitmap = null;
			try
			{
				URL url2 = new URL(url);
				bitmap = BitmapGet.getHttpBitmap(url2);
			} catch (MalformedURLException e)
			{
				e.printStackTrace();
			}
			msg.obj = bitmap;
		case Task.ADD_PRIVATE_MSG:
			String content = (String) task.getTaskParam().get("content");
			String name = (String) task.getTaskParam().get("name");
			StatusesService sendPrivateMsgService = new StatusesService(currentUser);
			msg.obj = sendPrivateMsgService.publishPrivateMsg(name, content);
			break;
		default:
			break;
		}
		
		handler.sendMessage(msg);

	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	public static void addTask(Task task)
	{
		tasks.add(task);
	}
	
	public static void addNewActiviy(BaseActivity activity)
	{
		allActivity.add(activity);
	}
	
	/**
	 * 
	 * @param name
	 * @return
	 */
	private static BaseActivity getActivityByName(String name)
	{
		if (!allActivity.isEmpty())
		{
			for (BaseActivity activity:allActivity)
			{
				if (activity.getClass().getName().indexOf(name)>0)
				{
					return activity;
				}
			}
		}
		
		return null;
	}
	
	
	public static void removeActivityByName(String className)
	{
		if (!allActivity.isEmpty())
		{
			BaseActivity activity = getActivityByName(className);
			if (activity != null)
			{
				allActivity.remove(activity);
				LogUtil.d(MainService.class, "remove Activity " + activity);
			}
		}
	}

	public static UserInfo getCurrentUser()
	{
		return currentUser;
	}

	public static void setCurrentUser(UserInfo currentUser)
	{
		MainService.currentUser = currentUser;
	}
	
	
	public  boolean isConnect(Context context) 
	{
		try
		{
			ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null)
			{
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected())
				{
					if (info.getState() == NetworkInfo.State.CONNECTED)
					{
						return true;
					}
				}
			}
		} catch (Exception e)
		{
			LogUtil.i(this, e.toString());
		}
		return false;
	} 



	

}
